package com.frontend.common.aop;

import com.frontend.common.utils.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;




@Aspect
public class ReturnvalueAop {

    // 定义切点，匹配所有service包下的所有方法
    @Pointcut("execution(* com.frontend..controller.*.*(..)) && " +
            "!within(com.frontend.common.controller.ChaController)")
    public void serviceMethods() {}
    // 环绕通知处理返回值
    @Around("serviceMethods()")
    public Object handleReturnValue(ProceedingJoinPoint joinPoint) throws Throwable {
        // 记录方法执行前信息
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        Object[] args = joinPoint.getArgs();
        System.out.println("开始执行方法: " + className + "." + methodName + "，参数: " + java.util.Arrays.toString(args));

        long startTime = System.currentTimeMillis();

        try {
            // 执行目标方法
            Object result = joinPoint.proceed();

            long endTime = System.currentTimeMillis();

            // 如果已经是R类型，直接返回
            if (result instanceof Result) {
                System.out.println("方法执行完成: " + className + "." + methodName +
                        "，耗时: " + (endTime - startTime) + "ms");
                return result;
            }

            // 否则封装成R类型
            Result response = Result.success(result);
            System.out.println("方法执行完成: " + className + "." + methodName +
                    "，返回值: " + result + "，耗时: " + (endTime - startTime) + "ms");

            return response;

        } catch (Exception e) {
            System.out.println("方法执行异常: " + className + "." + methodName +
                    "，异常信息: " + e.getMessage());
            return Result.error("执行异常: " + e.getMessage());
        }
    }
}
